package org.TCC_NOVO.client.visual;

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
//import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Function;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Tool;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.ToolbarButton;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.event.GridCellListenerAdapter;
import java.util.ArrayList;
import org.TCC_NOVO.client.modelo.Atividade_Roteiro;
import org.TCC_NOVO.client.GWTServiceAsync;
import org.TCC_NOVO.client.modelo.OcorrenciaTarefa;
import org.apache.catalina.HttpRequest;

public class RevisarTarefasPanel extends Panel{
    private final GWTServiceAsync controller;
    String IDF_Usuario;
    
    RevisarTarefasPanel self;
    FormPanel form;
    //FileUpload upload;
    VerticalPanel panel;
    TextArea arquivo;

    //Tela master
    Store storeMaster;
    GridPanel gridMaster;
    RecordDef recordDefMaster;

    //Tela Detail
    Store storeDetalhe;
    GridPanel gridDetalhe;
    RecordDef recordDefDetalhe;
    
    Toolbar toolbar;
    ArrayList<Atividade_Roteiro> ArrayTarefas = new ArrayList();
    ArrayList<OcorrenciaTarefa> ArrayOcorTarefas = new ArrayList();

    public RevisarTarefasPanel(GWTServiceAsync controller, String IDF_Usua) {
        this.controller = controller;
        this.IDF_Usuario = IDF_Usua;
        this.self = this;
        this.init();
    }

    private void init(){
        this.setBorder(true);
        this.setPaddings(2);

        recordDefMaster = new RecordDef(new FieldDef[]{
            new IntegerFieldDef("ID"),
            new StringFieldDef("projeto"),
            new StringFieldDef("unidade"),
            new StringFieldDef("titulo"),
            new StringFieldDef("descricao"),
            new StringFieldDef("data_Entrega"),
            new StringFieldDef("responsavel"),
            new StringFieldDef("status"),
            new StringFieldDef("IDF_Resp"),
            new StringFieldDef("data_Entrega_Form"),
        });

        storeMaster = new Store(recordDefMaster);
        gridMaster = new GridPanel();
        gridMaster.setStore(storeMaster);

        ColumnConfig[] columns = new ColumnConfig[]{
            new ColumnConfig("Nome Projeto", "projeto", 120, true),
            new ColumnConfig("Nome Unidade", "unidade", 190, true),
            new ColumnConfig("Título", "titulo", 150, true),
            new ColumnConfig("Descrição", "descricao", 270, true),
            new ColumnConfig("Status", "status", 120, true),
            new ColumnConfig("Data Entrega", "data_Entrega", 90, true),
            new ColumnConfig("Responsável", "responsavel", 90, true),
        };

        ColumnModel columnModel = new ColumnModel(columns);
        gridMaster.setColumnModel(columnModel);
        gridMaster.setFrame(true);
        gridMaster.setStripeRows(true);
        gridMaster.setSize(1020, 280);
        gridMaster.setAutoScroll(true);
        gridMaster.setTitle("Tarefas");
        gridMaster.addTool(new Tool(Tool.REFRESH, new Function() {
            @Override
            public void execute() {
                gridMaster.getEl().mask("Carregando", "x-mask-loading");
                CarrgarGridMaster();
                Timer timer = new Timer() {
                    @Override
                    public void run() {
                        gridMaster.getEl().unmask();
                    }
                };
                timer.schedule(1000);
            }
        }, "Atualizar"));

        gridMaster.addGridCellListener(new GridCellListenerAdapter(){
            public void onCellClick(GridPanel grid, int rowIndex, int colIndex, EventObject e){
                storeDetalhe.filter("IDF_Tarefa", grid.getSelectionModel().getSelected().getAsString("ID"));
            }
        });

        //Detalhes
        recordDefDetalhe = new RecordDef(new FieldDef[]{
            new IntegerFieldDef("ID"),
            new IntegerFieldDef("IDF_Tarefa"),
            new StringFieldDef("data"),
            new StringFieldDef("usuario"),
            new StringFieldDef("descricao"),
            new StringFieldDef("observacao"),
        });

        storeDetalhe = new Store(recordDefDetalhe);
        gridDetalhe = new GridPanel();
        gridDetalhe.setStore(storeDetalhe);

        ColumnConfig[] columnsDetalhe = new ColumnConfig[]{
            new ColumnConfig("Data Ocorrência", "data", 120, true),
            new ColumnConfig("Usuário", "usuario", 130, true),
            new ColumnConfig("Descrição", "descricao", 250, true),
            new ColumnConfig("Observação", "observacao", 340, true),
        };

        ColumnModel columnModelDetalhe = new ColumnModel(columnsDetalhe);
        gridDetalhe.setColumnModel(columnModelDetalhe);
        gridDetalhe.setFrame(true);
        gridDetalhe.setTitle("Ocorrências Tarefa");
        gridDetalhe.setStripeRows(true);
        gridDetalhe.setSize(1020, 300);
        gridDetalhe.setAutoScroll(true);

        toolbar = getToolbar();
        toolbar.setSize(gridMaster.getWidth(), 30);
        
        this.add(toolbar);
        this.add(gridMaster);
        this.add(gridDetalhe);

        //carrega as informações para o grid...
        CarrgarGridMaster();
        CarrgarGridDetalhe();
    }

    private class CallBackRetTarefas implements AsyncCallback<ArrayList<Atividade_Roteiro>> {
        @Override
	public void onFailure(Throwable e) {
		MessageBox.alert("Erro ao carregar dados... ", e.getMessage());
	}
        @Override
	public void onSuccess(ArrayList<Atividade_Roteiro> result) {
                CarregarDados(result);
                CarrgarGridDetalhe();
        }
    }

    private class CallBackRetOcoTarefas implements AsyncCallback<ArrayList<OcorrenciaTarefa>> {
        @Override
	public void onFailure(Throwable e) {
		MessageBox.alert("Erro ao carregar dados... ", e.getMessage());
	}
	public void onSuccess(ArrayList<OcorrenciaTarefa> result) {
                CarregarDadosDetalhe(result);
                storeDetalhe.filter("IDF_Tarefa", "VAZIO");
        }
    }

    private void CarregarDadosDetalhe(ArrayList<OcorrenciaTarefa> result){
        ArrayOcorTarefas = result;
        for (int i = 0; i < result.size(); ++i) {
            addRecordDetalhe(result.get(i));
        }
    }

    public void addRecordDetalhe(OcorrenciaTarefa OcoTarefa){
        Object[] rowData = new Object[]{
          OcoTarefa.getID(),
          OcoTarefa.getIDF_Tarefa(),
          OcoTarefa.getData(),
          OcoTarefa.getUsuario(),
          OcoTarefa.getDescricao(),
          OcoTarefa.getObservacao(),
        };
        Record record = recordDefDetalhe.createRecord(rowData[0].toString(), rowData);
        storeDetalhe.add(record);
    }

    private void CarregarDados(ArrayList<Atividade_Roteiro> result){
        ArrayTarefas = result;
        for (int i = 0; i < result.size(); ++i) {
            addRecord(result.get(i));
        }
    }

    public void CarrgarGridMaster(){
        storeMaster.removeAll();
        String sSQL = "select A.ID, A.Titulo, A.Descricao, B.Nick, "+
                      "A.IDF_Resp, A.Status, A.Data_entrega, D.Nome NmUnidade, E.Nome NmProjeto, D.ID IDF_Unidade "+
                      "from Atividade_Roteiro A "+
                      "inner join Usuario B on B.ID = A.IDF_Resp "+
                      "inner join Unidade D on D.ID = A.IDF_Unidade "+
                      "inner join Projeto E on E.ID = D.IDF_Projeto "+
                      "where (A.Status = 'Pronta para Revisão') ";
        controller.RetornarDadosTarefa(sSQL, new CallBackRetTarefas());
    }

    public void CarrgarGridDetalhe(){
        storeDetalhe.removeAll();
        String sSQL = "select * from ocorrencia_tarefa A "+
                      "inner join Usuario B on B.ID = A.IDF_Usuario";
        controller.RetornarDadosOcoTarefa(sSQL, new CallBackRetOcoTarefas());
    }

    public void addRecord(Atividade_Roteiro Tarefa){
        Object[] rowData = new Object[]{
          Tarefa.getId(),
          Tarefa.getNm_projeto(),
          Tarefa.getNm_unidade(),
          Tarefa.getTitulo(),
          Tarefa.getDescricao(),
          Tarefa.getData_entrega(),
          Tarefa.getResponsavel(),
          Tarefa.getStatus(),
          Tarefa.getIdf_responsavel(),
          Tarefa.getData_entrega_formatada(),
        };
        Record record = recordDefMaster.createRecord(rowData[0].toString(), rowData);
        storeMaster.add(record);
    }

    public Toolbar getToolbar(){
        final AsyncCallback callbackTarefasStatus = new AsyncCallback() {
            @Override
            public void onSuccess(Object result) {}
            @Override
            public void onFailure(Throwable caught) {
               MessageBox.alert("Erro ", caught.getMessage()); }
        };

        Toolbar toobar = new Toolbar();

        ToolbarButton btnBaixarArq = new ToolbarButton();
        btnBaixarArq.setText(" Baixar Arquivo Tarefa");
        btnBaixarArq.setIcon("Images/download.png");
        btnBaixarArq.setTooltip("Permite Baixar o Arquivo da Tarefa Selecionada");
        btnBaixarArq.addListener(new ButtonListenerAdapter(){
            @Override
            public void onClick(Button button, EventObject e){
                if (gridMaster.getSelectionModel().getSelected() == null){
                    MessageBox.alert("Necessário Selecionar Algum Registro! ");
                }else{
                    //arquivo.setValue(gridMaster.getSelectionModel().getSelected().getAsString("ID"));
                    form = new FormPanel();
                    form.setAction("ServletDownload");
                    form.setEncoding(FormPanel.ENCODING_MULTIPART);
                    form.setMethod(FormPanel.METHOD_POST);

                    panel = new VerticalPanel();
                    form.setWidget(panel);
                    FileUpload upload2 = new FileUpload();
                    panel.add(upload2);
                    upload2.setName("Tarefas"+","+gridMaster.getSelectionModel().getSelected().getAsString("ID"));
                    form.submit();

                    form.addFormHandler(new FormHandler() {
                        @Override
                        public void onSubmitComplete(FormSubmitCompleteEvent event) {
                            System.out.println("Download completo!");
                            //panel.remove(upload);
                        }
                        @Override
                        public void onSubmit(FormSubmitEvent event) {
                        //System.out.println(event.getResults());
                        //wainting.show();
                        //wainting.Executar();
                        }
                   });                   
                }
            }
        });

        //form = new FormPanel();
        //form.setAction("ServletDownload");
        //form.setEncoding(FormPanel.ENCODING_MULTIPART);
        //form.setMethod(FormPanel.METHOD_POST);

        //panel = new VerticalPanel();
        //form.setWidget(panel);
        //upload = new FileUpload();
        //panel.add(upload);
        
        //Adiciona o evento no form.
        /*form.addFormHandler(new FormHandler() {
            @Override
            public void onSubmitComplete(FormSubmitCompleteEvent event) {
                System.out.println("Download completo!");
                //panel.remove(upload);
            }

            @Override
            public void onSubmit(FormSubmitEvent event) {
                //System.out.println(event.getResults());
                //wainting.show();
                //wainting.Executar();
            }
        });*/
        
        ToolbarButton btnTarProb = new ToolbarButton();
        btnTarProb.setText(" Trâmite Tarefa");
        btnTarProb.setIcon("Images/tarefaStatus.png");
        btnTarProb.setTooltip("Permite Informar se a Tarefa está com Problemas ou está OK");
        btnTarProb.addListener(new ButtonListenerAdapter(){
            public void onClick(Button button, EventObject e){
                if (gridMaster.getSelectionModel().getSelected() == null){
                    MessageBox.alert("Necessário Selecionar Algum Registro! ");
                }else{
                    RevisarTarefasForm RevTarProb = new RevisarTarefasForm(controller, self, gridMaster.getSelectionModel().getSelected().getAsInteger("ID"), IDF_Usuario);
                    RevTarProb.show();
                }
            }
        });
        
        toobar.addButton(btnBaixarArq);
        toobar.addSeparator();
        //toobar.addButton(btnConcluir);
        toobar.addButton(btnTarProb);

        return toobar;
    }

    
}
